package controllers

import (
	"log"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

func init() {
	orm.RegisterModel(new(AdminUser))
}

//AdminPreparer
type AdminPreparer interface {
	AdminPrepare()
}

//AdminBase
type AdminBase struct {
	beego.Controller
	User AdminUser
}

//Prepare get ready to run interface
func (a *AdminBase) Prepare() {
	//AdminBase prepare
	if app, ok := a.AppController.(AdminPreparer); ok {
		app.AdminPrepare()
	}
	if a.Ctx.Request.URL.String() != `/admin/login` {
		user := a.GetSession("AdminUser")
		if user == nil {
			a.Abort(`{"authenticated":false,"message":"not auth"}`)
		} else {
			a.User = user.(AdminUser)
			a.Layout = `layout/admin.layout.tpl`
		}
	}
}

//AdminUser 管理员模型
type AdminUser struct {
	ID       int    `form:"-" orm:"column(ID)"`
	Email    string `form:"email"`
	Password string `form:"password"`
}

//Login 超市内部登陆
func (a *AdminBase) Login() {
	a.Layout = ``
	if a.Ctx.Input.Method() == `POST` {
		u := AdminUser{}
		if err := a.ParseForm(&u); err == nil {
			o := orm.NewOrm()
			if err := o.QueryTable(`admin_user`).SetCond(orm.NewCondition().And("Email", u.Email).And("Password", u.Password)).One(&u); err == nil {
				a.SetSession("AdminUser", u)
				a.Redirect("/admin/sup/index", 301)
			} else {
				log.Println(err)
			}
		} else {
			log.Println(err)
		}
		a.Redirect("/admin/login", 301)
	}
	a.TplName = `admin/login.tpl`
}
